package com.ruoyi.learn.java.algorithm.dp;

/**
 *  1. 斐波那契数列（Fibonacci）
 * 问题：求第 n 个斐波那契数，F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2)。
 */
public class Fibonacci {
    public static int fib(int n) {
        if (n <= 1) return n;
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    // 空间优化版本
    public static int fibOptimized(int n) {
        if (n <= 1) return n;
        int prev2 = 0, prev1 = 1;
        int curr = 0;
        for (int i = 2; i <= n; i++) {
            curr = prev1 + prev2;
            prev2 = prev1;
            prev1 = curr;
        }
        return curr;
    }

    public static void main(String[] args) {
        System.out.println(fib(30)); // 输出: 55
    }
}
